package com.itwmk.service.impl.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itwmk.entity.*;
import com.itwmk.mapper.OrderMapper;
import com.itwmk.service.impl.*;
import com.itwmk.utils.BaseContext;
import com.itwmk.utils.CustomException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author wmk
 */
@Service
@Transactional
public class OrderImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private OrderService orderService;
    @Override
    public void mySubmit(Orders orders) {
        Long id = BaseContext.getId();

        LambdaQueryWrapper<ShoppingCart> shoppingWrapper = new LambdaQueryWrapper<>();
        shoppingWrapper.eq(ShoppingCart::getUserId,id);
        List<ShoppingCart> cartList = shoppingCartService.list(shoppingWrapper);
        if (cartList==null){
            throw new CustomException("购物车里没有商品");
        }
        AddressBook address = addressBookService.getById(orders.getAddressBookId());
        if (address==null){
            throw new CustomException("该地址未保存");
        }

        User user = userService.getById(id);
        //生成订单号
        long idNum = IdWorker.getId();

        AtomicInteger amount=new AtomicInteger(0);
        ArrayList<OrderDetail> listDetail = new ArrayList<>();
        //设置订单详细信息
        for (ShoppingCart c:cartList) {
            OrderDetail detail = new OrderDetail();
            //这里将订单号作为order_detail中orders的标记
            detail.setOrderId(idNum);
            detail.setNumber(c.getNumber());
            detail.setDishFlavor(c.getDishFlavor());
            detail.setSetmealId(c.getSetmealId());
            detail.setName(c.getName());
            detail.setImage(c.getImage());
            detail.setAmount(c.getAmount());
            //计算并累加购物车中商品价格
            amount.addAndGet(c.getAmount().multiply(new BigDecimal(c.getNumber())).intValue());
            listDetail.add(detail);
        }
        //保存订单明细信息
        orderDetailService.saveBatch(listDetail);

        //设置订单概况信息
        orders.setNumber(String.valueOf(idNum));
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setUserId(id);
        orders.setUserName(user.getName());
        orders.setConsignee(address.getConsignee());
        orders.setPhone(address.getPhone());
        orders.setAddress((address.getProvinceName()!=null?address.getProvinceName():"")
                +(address.getCityName()!=null?address.getCityName():"")
                +(address.getDistrictName()!=null?address.getDistrictName():"")
                +(address.getDetail()!=null?address.getDetail():"")
        );
        orders.setAmount(new BigDecimal(amount.get()));
        //保存订单概况信息
        save(orders);

        //清空购物车
        shoppingCartService.remove(shoppingWrapper);



    }

    /**
     * 查询订单信息
     * @param page
     * @param pageSize
     */
    @Override
    public Page queryWhitDetail(int page, int pageSize) {
        Page<OrdersDto> dtoPage = new Page<>(page, pageSize);
        Page<Orders> orderPage = new Page<>(page, pageSize);
        Long id = BaseContext.getId();
        LambdaQueryWrapper<Orders> orderWrapper = new LambdaQueryWrapper<>();
        orderWrapper.eq(Orders::getUserId,id);
        orderService.page(orderPage,orderWrapper);
        BeanUtils.copyProperties(orderPage,dtoPage,"records");
        List<Orders> records = orderPage.getRecords();
        ArrayList<OrdersDto> dtoRecords = new ArrayList<>();

        for (Orders o:records) {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(o,ordersDto);
            LambdaQueryWrapper<OrderDetail> detailWrapper = new LambdaQueryWrapper<>();
            detailWrapper.eq(OrderDetail::getOrderId,o.getNumber());
            List<OrderDetail> details = orderDetailService.list(detailWrapper);

            ordersDto.setOrderDetails(details);
            dtoRecords.add(ordersDto);

        }

        dtoPage.setRecords(dtoRecords);


        return dtoPage;

    }
}
